<template>
  <div class="login">
    <!-- 登录页头部 -->
    <div class="login-header">
      <img class="login_logo" src="../../assets/images/logo.png" alt="" />
      <!-- <div class="flex-y-center">
        <el-switch v-model="isDark" inline-prompt active-icon="Moon" inactive-icon="Sunny" @change="toggleTheme" />
        <lang-select class="ml-2 cursor-pointer" />
      </div> -->
    </div>

    <!-- 登录页内容 -->
    <div class="login-content">
      <div class="login-img">
        <img src="../../assets/images/loginBig.jpg" style="width: 100%; height: 100%" />
      </div>
      <div class="login-form">
        <el-form ref="loginFormRef" :model="loginData" :rules="loginRules">
          <div class="form-title">
            <h2 class="title">账号登录</h2>
            <el-dropdown style="position: absolute; right: 0">
              <div class="code">
                <!-- <el-icon>
                  <arrow-down />
                </el-icon> -->
                <!-- 二维码 -->
                <img class="qrCode" src="../../assets/images/qrCode.png" alt="" />
              </div>
            </el-dropdown>
          </div>

          <!-- 用户名 -->
          <el-form-item prop="username">
            <div class="input-wrapper">
              <el-icon class="mx-2">
                <User />
              </el-icon>
              <el-input
                ref="username"
                v-model="loginData.username"
                :placeholder="$t('login.username')"
                name="username"
                size="large"
                class="h-[48px]"
              />
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item prop="pwd">
              <div class="input-wrapper">
                <el-icon class="mx-2">
                  <Lock />
                </el-icon>
                <el-input
                  v-model="loginData.pwd"
                  :placeholder="$t('login.password')"
                  type="password"
                  name="password"
                  size="large"
                  class="h-[48px] pr-2"
                  show-password
                  @keyup="checkCapslock"
                  @keyup.enter="handleLoginSubmit"
                />
              </div>
            </el-form-item>
          </el-tooltip>

          <!-- 验证码 -->
          <el-form-item prop="verifyCode">
            <div class="input-wrapper">
              <svg-icon icon-class="captcha" class="mx-2" />
              <el-input
                v-model="loginData.verifyCode"
                auto-complete="off"
                size="large"
                class="flex-1"
                :placeholder="$t('login.captchaCode')"
                @keyup.enter="submit"
              />

              <el-image :src="captchaBase64" class="captcha-img" @click="getCaptcha" />
            </div>
          </el-form-item>

          <div class="flex-x-between w-full py-1">
            <el-checkbox>
              {{ $t("login.rememberMe") }}
            </el-checkbox>

            <el-link type="primary" href="/forget-password">
              {{ $t("login.forgetPassword") }}
            </el-link>
          </div>

          <!-- 登录按钮 -->
          <el-button
            :loading="loading"
            type="success"
            size="large"
            class="w-full"
            @click.prevent="submit"
          >
            {{ $t("login.login") }}
          </el-button>

          <!-- 第三方登录 -->
          <el-divider>
            <el-text size="small">{{ $t("login.otherLoginMethods") }}</el-text>
          </el-divider>
          <div class="third-party-login">
            <svg-icon icon-class="wechat" class="icon" />
            <svg-icon icon-class="qq" class="icon" />
            <svg-icon icon-class="github" class="icon" />
            <svg-icon icon-class="gitee" class="icon" />
          </div>
        </el-form>
      </div>
    </div>

    <!-- 登录页底部 -->
    <div class="login-footer">
      <span>Copyright @ 乐康养老 京ICP备15048223号-1</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { LocationQuery, useRoute } from "vue-router";

import AuthAPI, { type LoginData } from "@/api/auth";
import router from "@/router";

import type { FormInstance } from "element-plus";

import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

import { useSettingsStore, useUserStore, useDictStore } from "@/store";
import { getCaptchaData } from "@/api/auth/captcha";
import { loginApi } from "@/api/auth/auth";
import { setToken } from "@/utils/auth";
import { debounce } from "@/utils/debounce";
import { useCryptoStore} from "@/store";
const cryptoStore=useCryptoStore();
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const dictStore = useDictStore();

const route = useRoute();
const { t } = useI18n();
const loginFormRef = ref<FormInstance>();

const isDark = ref(settingsStore.theme === ThemeEnum.DARK); // 是否暗黑模式
const loading = ref(false); // 按钮 loading 状态
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串

const logo = ref(new URL("../../assets/logo.png", import.meta.url).href);
const loginImage = ref(new URL("../../assets/images/loginBi", import.meta.url).href);

const loginData = ref<LoginData>({
  username: "lvzhuosheng",
  pwd: "123456",
  verifyCodeId: "",
  verifyCode: "",
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    pwd: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 1,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    verifyCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

//监听验证码
// watch(loginData.value, (data) => {
//   if (!data.verifyCode) {
//     loading.value = false;
//   }
// });

// 获取验证码
async function getCaptcha() {
  let res = await getCaptchaData().catch(() => undefined);

  if (res) {
    loginData.value.verifyCodeId = res.id;
    captchaBase64.value = res.imageCode;
  }
}

// 登录
  function handleLoginSubmit() {

  loginFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;

 
        
      loginApi({...loginData.value})
        .then((data) => {
        
          localStorage.setItem("userInfo", JSON.stringify(data.model));
          setToken(data.token);
          // 跳转到登录前的页面
          router.push({ path: "/dashboard" });
        })
        .catch(() => {
          console.log("999922");
          getCaptcha();
        }).finally(()=>{
         ; loading.value = false
        });
        
     
    

    }
  });
}

const submit = debounce(handleLoginSubmit, 500, true);

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

// 主题切换
const toggleTheme = () => {
  const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

// 检查输入大小写
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

// 设置登录凭证
const setLoginCredentials = (username: string, password: string) => {
  loginData.value.username = username;
  loginData.value.pwd = password;
};

onMounted(() => {
  getCaptcha();
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background-color: #eee;
  //background: url("@/assets/images/login-background-light.jpg") no-repeat center right;

  .login-header {
    position: absolute;
    top: 0;
    display: flex;
    width: 100%;
    height: 10%;
    padding: 10px 20px;
    background-color: #fff;

    .login_logo {
      display: block;
      width: auto;
      height: 100%;
    }
  }

  .login-content {
    display: flex;
    width: 1190px;
    height: 473px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 5px;
    // box-shadow: var(--el-box-shadow-light);
    box-shadow: 0 0 20px 10px #ccc;

    @media (width <=768px) {
      flex-direction: column;
      max-width: 100%;
      height: 100vh;
      padding: 0 30px;
      border-radius: 0;
      box-shadow: none;
    }

    .login-img {
      width: 70%;
      height: 473px;
    }

    .login-form {
      display: flex;
      flex-direction: column;
      justify-content: center;
      max-width: 461px;
      padding: 30px;

      @media (width <=768px) {
        width: 100%;
        padding: 0 20px;
      }

      .form-title {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 0 20px;
        text-align: center;

        .title {
          font-size: 20px;
        }

        .code {
          position: relative;

          .qrCode {
            position: absolute;
            top: -46px;
            right: -26px;
            width: 60px;
            height: 60px;
          }
        }
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        width: 100%;
      }

      .captcha-img {
        height: 48px;
        cursor: pointer;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
      }

      .third-party-login {
        display: flex;
        justify-content: center;
        width: 100%;
        color: var(--el-text-color-secondary);

        *:not(:first-child) {
          margin-left: 20px;
        }

        .icon {
          cursor: pointer;
        }
      }
    }
  }

  .login-footer {
    position: absolute;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 10%;
    font-size: 16px;
    background-color: #fff;
  }
}

:deep(.el-form-item) {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

html.dark {
  .login {
    background: url("@/assets/images/login-background-dark.jpg") no-repeat center right;

    .login-content {
      background: transparent;
      box-shadow: var(--el-box-shadow);
    }
  }
}
</style>
